//index.js
//获取应用实例
const app = getApp()
let animationShowHeight = 300;

Page({
  data: {
    loadingHidden: false,
    animationData: "",
    winWidth: 0,
    winHeight: 0,
    dataNumber: 0,
    currentTab: 0,
    priceId: 2,
    stepId: 8,
    rewardList: [],
    reward: 7,
    userId: 0,
    rewardId: 1,
    marathonPercent: 0,
    totalPrice: 0,
    homeData: null,
    money:0,
  },
  onLoad: function () {
    var that = this;
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  onShow: function () {
    var that = this;
    var intervalId = setInterval(function () {
      if (that.data.homeData == null || app.globalData.indexDataHaveChange) {
        that.getHomeData();
      } else {
        that.setData({
          loadingHidden: true
        });
        clearInterval(intervalId);
        that.AutoUpdateStep();
      }
    }, 300);
  },
  /**
   * 获取首页信息
   */
  getHomeData: function () {
    var that = this;
    if (app.globalData.homeData != null && app.globalData.appGetDataFinish) {
      that.setData({
        homeData: app.globalData.homeData,
        dataNumber: app.globalData.homeData.priceRank.length,
        rewardList: app.globalData.homeData.rewardList,
        userId: app.globalData.homeData.user.id,
        user: app.globalData.homeData.user,
        money: app.globalData.homeData.user.balance,
        marathonPercent: (app.globalData.homeData.step * 100 / 126585).toFixed(2),
        totalPrice: (app.globalData.homeData.priceAmount / 100).toFixed(2),
        loadingHidden: true
      })
      app.globalData.indexDataHaveChange = false;
    }
  },
  /**
   * 获取用户信息 
   */
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /** 
   * 滑动切换tab 
   */
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });
  },
  /** 
   * 点击tab切换 
   */
  swichNav: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  /**
   * 显示报名弹窗
   */
  showSignUpModal: function (e) {
    // 显示遮罩层  
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(animationShowHeight).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  /**
   * 隐藏报名弹窗
   */
  hideSignUpModal: function () {
    // 隐藏遮罩层  
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY(animationShowHeight).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  /**
   * 报名窗口-步数点击事件
   */
  clickStepOption: function (e) {
    var rewardList = this.data.rewardList
    this.setData({
      stepId: e.target.id
    })
    for (var i = 0; i < rewardList.length; i++) {
      if (this.data.priceId == rewardList[i].priceId && this.data.stepId == rewardList[i].stepId) {
        this.setData({
          reward: rewardList[i].reward,
          rewardId: rewardList[i].id
        })
      }
    }
  },
  /**
   * 报名窗口-押金点击事件
   */
  clickPriceOption: function (e) {
    var rewardList = this.data.rewardList
    this.setData({
      priceId: e.target.id
    })
    for (var i = 0; i < rewardList.length; i++) {
      if (this.data.priceId == rewardList[i].priceId && this.data.stepId == rewardList[i].stepId) {
        this.setData({
          reward: rewardList[i].reward,
          rewardId: rewardList[i].id
        })
      }
    }
  },
  /**
   * 上传报名目标
   */
  postSignUp: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.API_URL + 'signUp/postSignUp',
      data: {
        token: that.data.user.token,
        rewardId: that.data.rewardId,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (r) {
        if (r.data.code == 0) {
          if (r.data.data == '设定目标成功') {
            // TODO : 更新数据
            that.setData({
              loadingHidden: false,
            })
            var intervalId = setInterval(function () {
              if (app.globalData.appGetDataFinish == true) {
                that.setData({
                  loadingHidden: true
                });
                clearInterval(intervalId);
                wx.showToast({
                  title: '设定目标成功'
                })
              }
            }, 300);
            app.globalData.indexDataHaveChange = true;
            app.globalData.appGetDataFinish = false;
            app.getHomeData();
            that.hideSignUpModal()
            that.onShow();
          } else {
            wx.requestPayment({
              'timeStamp': r.data.data.timeStamp,
              'nonceStr': r.data.data.nonceStr,
              'package': 'prepay_id=' + r.data.data.prepayId,
              'signType': r.data.data.signType,
              'paySign': r.data.data.paySign,
              'success': function (res) {
                // TODO : 更新数据
                that.setData({
                  loadingHidden: false,
                })
                var intervalId = setInterval(function () {
                  if (app.globalData.appGetDataFinish == true) {
                    that.setData({
                      loadingHidden: true
                    });
                    clearInterval(intervalId);
                    wx.showToast({
                      title: '设定目标成功'
                    })
                  }
                }, 300);
                app.globalData.indexDataHaveChange = true;
                app.globalData.appGetDataFinish = false;
                app.getHomeData();
                that.hideSignUpModal()
                that.onShow();
              },
              'fail': function (res) {
                // TODO : 提醒用户
                wx.showToast({
                  title: res
                })
                that.hideSignUpModal()
                that.onShow();
              }
            })
          }
        }
        else {
          wx.showToast({
            title: r.data.msg
          })
        }
      }
    })
  },
  /**
   * 用户手动打卡
   */
  postPunch: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.getWeRunData({
      success: res => {
        wx.request({
          url: app.globalData.API_URL + 'home/postPunch',
          data: {
            'token': that.data.user.token,
            'encryptedData': res.encryptedData,
            'iv': res.iv,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'post',
          success: function (r) {
            if (r.data.code == 0) {
              wx.hideLoading()
              wx.showToast({
                title: '打卡成功~'
              })
              that.data.homeData.signUp.step = r.data.data;
              app.globalData.homeData.signUp.step = r.data.data;
            }
            else {
              wx.showToast({
                title: r.data.msg
              })
            }
          }
        })
      }
    })
  },
  /**
   * 自动更新用户步数
   */
  AutoUpdateStep: function (e) {
    var that = this;
    var intervalId = setInterval(function () {
      wx.getWeRunData({
        success: res => {
          wx.request({
            url: app.globalData.API_URL + 'home/postPunch',
            data: {
              'token': that.data.user.token,
              'encryptedData': res.encryptedData,
              'iv': res.iv,
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'post',
            success: function (r) {
              console.log(new Date() + 'AutoUpdateStep:' + r.data.data)
              if (r.data.code == 0) {
                that.data.homeData.step = r.data.data
                app.globalData.homeData.step = r.data.data
              }
            }
          })
        }
      })
    }, 60000);
  },

  /**
   * 用户协议复选框
   */
  checkChange:function(e){
    console.log(e.detail.checked)
  }
})
